package com.kefu.call.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.basic.mapper.BasicStatusConfigMapper;
import com.kefu.basic.model.BasicStatusConfig;
import com.kefu.call.mapper.CallAgentAuxStatusMapper;
import com.kefu.call.model.CallAgentAuxStatus;
import com.kefu.call.vo.CallStatusConfigInsertVo;
import com.kefu.call.vo.CallStatusConfigSearchVo;
import com.kefu.call.vo.CallStatusConfigUpdateVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;

@Service
public class CallConfigStatusService extends AbstractKefuService<CallAgentAuxStatus> {
    @Resource
    private BasicStatusConfigMapper basicStatusConfigMapper;
    @Resource
    private CallAgentAuxStatusMapper callAgentAuxStatusMapper;

    public void addStatusConfig(CallStatusConfigInsertVo callStatusConfigVo) {
        Instant start = Instant.now();
        logger.info("添加呼叫小休自定义状态:{}", callStatusConfigVo);
        String tid = KefuContext.getTid();
        Assert.isTrue(basicStatusConfigMapper.selectCount(Wrappers.lambdaQuery(BasicStatusConfig.class)
                        .eq(BasicStatusConfig::getStatusName, callStatusConfigVo.getStatusName())
                        .eq(BasicStatusConfig::getTenantId, tid)
                        .eq(BasicStatusConfig::getStatusType, 2)) > 0,
                "呼叫小休状态已经存在！");
        //
        BasicStatusConfig info = callStatusConfigVo.convert();
        // 查询呼叫小休表中最大的sort
        CallAgentAuxStatus maxStatus = callAgentAuxStatusMapper.selectOne(
                Wrappers.lambdaQuery(CallAgentAuxStatus.class)
                .orderByDesc(CallAgentAuxStatus::getSort)
                .last("limit 1"));
        Assert.isTrue(Objects.isNull(maxStatus)
                || Objects.isNull(maxStatus.getSort()), "呼叫小休状态异常！");
        Integer statusCode = maxStatus.getSort() + 1;
        CallAgentAuxStatus auxStatus = callStatusConfigVo.convertCall(statusCode);
        callAgentAuxStatusMapper.insert(auxStatus);
        info.setCallId(String.valueOf(auxStatus.getOid()));
        logger.info("call_basicStatus_Add fs Table:{}", callStatusConfigVo, JacksonUtil.toString(auxStatus));
        info.setStatusCode(String.valueOf(statusCode));
        basicStatusConfigMapper.insert(info);
        logger.info("call_basicStatus_Add:{},{}ms", info, Duration.between(start, Instant.now()).toMillis());
    }

    public void deleteStatusConfig(String id) {
        BasicStatusConfig info = basicStatusConfigMapper.selectByPrimaryKey(id);
        Assert.isTrue(Objects.isNull(info),"已删除!");
        Assert.isTrue(1 == info.getIsDefault(), "系统默认状态不能删除!");
        Assert.isTrue(1 == info.getStatus(), "启动中不能删除！");
        basicStatusConfigMapper.deleteById(id);
        callAgentAuxStatusMapper.deleteById(Integer.valueOf(info.getCallId()));
        logger.info("删除呼叫状态: {}", JacksonUtil.toString(info));
    }

    public String updateStatusConfig(CallStatusConfigUpdateVo update) {
        String id = update.getId();
        BasicStatusConfig statusConfig = basicStatusConfigMapper.selectByPrimaryKey(id);
        Assert.isTrue(Objects.isNull(statusConfig), "状态已被删除！");
        if (1 == statusConfig.getIsDefault()) {
            Assert.isTrue(!update.getStatusName().equals(statusConfig.getStatusName()),
                    "不能修改默认状态的名称！");
            Assert.isTrue(0 == update.getStatus(), "不能关闭默认的状态！");
        }
        LambdaQueryWrapper<BasicStatusConfig> wrapper = Wrappers.lambdaQuery(BasicStatusConfig.class);
        wrapper.eq(BasicStatusConfig::getStatusName, update.getStatusName());
        wrapper.eq(BasicStatusConfig::getTenantId, KefuContext.getTid());
        wrapper.eq(BasicStatusConfig::getStatusType, 1);
        List<BasicStatusConfig> list = basicStatusConfigMapper.selectList(wrapper);
        boolean flag = true;
        if (CollUtil.isNotEmpty(list)) {
            for (BasicStatusConfig config : list) {
                if (!config.getId().equals(update.getId())) {
                    flag = false;
                    break;
                }
            }
        }
        Assert.isTrue(!flag, "状态["+ update.getStatusName() +"]已经存在！");
        if (StrUtil.isNotBlank(statusConfig.getCallId())
                && StrUtil.isNotBlank(update.getStatusName())) {
            CallAgentAuxStatus auxStatus = new CallAgentAuxStatus();
            auxStatus.setVal(update.getStatusName());
            auxStatus.setOid(Integer.valueOf(statusConfig.getCallId()));
            callAgentAuxStatusMapper.updateById(auxStatus);
            logger.info("call_basicStatus_Update fs Table :{}", JacksonUtil.toString(auxStatus));
        }
        BasicStatusConfig info = update.convert();
        basicStatusConfigMapper.updateById(info);
        logger.info("call_basicStatus_Update :{}", JacksonUtil.toString(info));
        return info.getId();
    }

    public Page<BasicStatusConfig> listStatusConfig(CallStatusConfigSearchVo search) {
        Page<BasicStatusConfig> page = new Page<>(search.getPageNo(), search.getPageSize(), true);
        return basicStatusConfigMapper.selectPage(page, search.lambdaQuery());
    }
}
